package com.rico.smart.utils;

public class IByteBuffer {

    private byte[] buf;
    private int offset=0;

    public IByteBuffer(byte[] buf){
        this.buf=buf;
    }

    public int readInt(){
        byte intBytes[]=get(offset,4);
        offset=4;
        return bytesToInt(intBytes);
    }

    public void readBytes(byte bytes[]){
        int len=bytes.length;
        for(int i=0;i<len;i++){
            bytes[i]=buf[i+offset];
        }
        offset=offset+len;
    }

    public int readableBytes(){
        return this.buf.length-offset;
    }

    public byte[] get(int offset,int len){
        byte bytes[]=new byte[len];
        for(int i=0;i<len;i++){
            bytes[i]=buf[i+offset];
        }
        offset=offset+len;
        return bytes;
    }

    public void reset(){
        this.offset=0;
    }


    public static int bytesToInt(byte[] src) {
        int value = (int) ((src[3] & 0xFF)
                | ((src[2] & 0xFF)<<8)
                | ((src[1] & 0xFF)<<16)
                | ((src[0] & 0xFF)<<24));
        return value;
    }

    public static byte[] intToBytes( int value )
    {
        byte[] src = new byte[4];
        src[3] =  (byte) ((value>>24) & 0xFF);
        src[2] =  (byte) ((value>>16) & 0xFF);
        src[1] =  (byte) ((value>>8) & 0xFF);
        src[0] =  (byte) (value & 0xFF);
        return src;
    }

}
